﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace IngredSubTool
{
    /// <summary>
    /// Interaction logic for UserSubmissionView.xaml
    /// </summary>
    public partial class UserSubmissionView : UserControl, IAppPage
    {
        private String ingredientEntryDefault = "Enter Ingredient";
        private String subEntryDefault = "Enter Substitution";
        private String ratioEntryDefault = "Amount";
        private String descEntryDefault = "Enter Description";

        private String emptyIngredientError = "Ingredient or Substitution fields must not be empty\n";
        private String invalidRatioError = "Ratio amounts must be entered and must be numeric\n";
        private String emptyDescError = "Please give a description of this substitution\n";
        private String confirmMsg = "Are you sure you want to submit? If yes press Submit again, otherwise keep editing.";
        private String goBackConfirm = "Are you sure you want to go back? Press Back again to confirm.";
        private String numericRegex = @"^\d+$";
        private String ingredient;
        private String substitution;
        private String ingredientAmount;
        private String substitutionAmount;
        private String ratio;
        private String description;
        private String errors;
        private Boolean hasErrors = false;

        private List<CheckBox> categoryCheckBoxes;

        public UserSubmissionView()
        {
            InitializeComponent();
            createCategoryCheckBoxes();
            initializeRatioUnits();
            Menu.Content = new SideMenu();
  
        }

        private void Submit(object sender, RoutedEventArgs e)
        {
            ingredient = Ingredient_Entry.Text;
            substitution = Substitution_Entry.Text;
            ingredientAmount = Ratio_Ingredient_Entry.Text;
            substitutionAmount = Ratio_Substitution_Entry.Text;
            
            description = Description_Entry.Text;
            double subRatio = 0;
            double ingRatio = 0;

            // clear errors first
            errors = "";

            // check for valid input, ingredient and substitution must not be left blank
            if (ingredient.Length == 0 || substitution.Length == 0
                || ingredient.Equals("Enter Ingredient") || substitution.Equals("Enter Substitution")) {
                errors = errors + emptyIngredientError;
                hasErrors = true;
            }

            // check ratio is valid - only if it was entered
            if (Ratio_Substitution_Entry.Text.Equals("Amount") || !double.TryParse(Ratio_Substitution_Entry.Text, out subRatio)
                || Ratio_Ingredient_Entry.Text.Equals("Amount") || !double.TryParse(Ratio_Ingredient_Entry.Text, out ingRatio))
            {
                errors = errors + invalidRatioError;
                hasErrors = true;
            }

            // check description is not empty
            if (Description_Entry.Text.Equals(descEntryDefault) || description.Length == 0)
            {
                errors = errors + emptyDescError;
                hasErrors = true;
            }

            if (hasErrors)
            {
                InfoBox.Foreground = Brushes.Red;
                InfoBox.Text = errors;
                hasErrors = false;
            }
            else
            {
                if (confirmBox.Text != confirmMsg)
                {
                    confirmBox.Text = confirmMsg;
                }
                // no errors proceed to submit
                else
                {
                    ratio = ingRatio.ToString() + ":" + subRatio.ToString() + ":" + Ingredient_Units.SelectedValue.ToString() + ":" + Substitution_Units.SelectedValue.ToString();              
                    Substitution newSub = new Substitution(ingredient, substitution, description, getCheckedCategories(), ratio);
                    Boolean privateSub = false;

                    if (PrivateSubCheckBox.IsChecked == true)
                    {
                        privateSub = true;
                    }

                    MainWindow.session.privateSubs.Add(newSub);
                    PageSwitcher.SwitchForward(new SubmitSuccessView(privateSub));
                }
            }
        }

        private String getCheckedCategories()
        {
            StringBuilder sb = new StringBuilder();
            foreach (CheckBox box in categoryCheckBoxes)
            {
                if (box.IsChecked == true)
                {
                    sb.Append(box.Content).Append(",");
                }
            }
            return sb.ToString().TrimEnd(new char[] { ',' });
        }

        private void createCategoryCheckBoxes()
        {
            categoryCheckBoxes = new List<CheckBox>();
            List<SearchCategory> categories = DataLoader.SearchCategories;
            foreach (SearchCategory category in categories)
            {
                // create box
                CheckBox box = new CheckBox();
                box.Content = category.Name;
                box.IsThreeState = false;
                categoryCheckBoxes.Add(box);
                CategoriesList.Children.Add(box);
            }
        }

        private void Back(object sender, RoutedEventArgs e)
        {
            if (confirmBox.Text == goBackConfirm)
            {
                PageSwitcher.SwitchBack();
            }
            else
            {
                confirmBox.Text = goBackConfirm;
            }
        }

        private Boolean checkRatioInput(String input)
        {
            return Regex.IsMatch(input, numericRegex);
        }

        private void Focused(object sender, RoutedEventArgs e)
        {
            if(confirmBox.Text == confirmMsg || confirmBox.Text == goBackConfirm)
            {
                confirmBox.Text = "";
            }
            String msg = "";
            TextBox box = (TextBox)sender;

            // change box foreground
            box.Foreground = Brushes.Black;

            String currentText = box.Text;
            // clear box of default text
            if (currentText == ingredientEntryDefault || currentText == subEntryDefault
                || currentText == ratioEntryDefault || currentText == descEntryDefault)
            {
                box.Text = "";
            }

            if (sender.Equals(Ingredient_Entry))
            {
                msg = "Enter the ingredient to be substituted";
            }
            else if (sender.Equals(Substitution_Entry))
            {
                msg = "Enter the substitution for the ingredient";
            }
            else if (sender.Equals(Ratio_Ingredient_Entry))
            {
                msg = "Enter amount of ingredient to be substituted";
            }
            else if (sender.Equals(Ratio_Substitution_Entry))
            {
                msg = "Enter amount of substitution required";
            }
            else if (sender.Equals(Description_Entry))
            {
                msg = "Enter additional details regarding this substitution";
            }

            // update infobox 
            InfoBox.Foreground = Brushes.Black;
            InfoBox.Text = msg;

        }

        private void initializeRatioUnits()
        {
            // get units of measure list, add "each"
            DataLoader.LoadUnits();
            List<UnitsOfMeasure> ingredientUnits = DataLoader.Units;
            UnitsOfMeasure each = new UnitsOfMeasure("Each", 1);
            ingredientUnits.Add(each);
            Ingredient_Units.ItemsSource = ingredientUnits;
            Ingredient_Units.DisplayMemberPath = "UnitName";
            Ingredient_Units.SelectedValuePath = "UnitName";
            Ingredient_Units.SelectedIndex = 0;

            // second box should not have "each"
            DataLoader.LoadUnits(); // reload units
            Substitution_Units.ItemsSource = DataLoader.Units;
            Substitution_Units.DisplayMemberPath = "UnitName";
            Substitution_Units.SelectedValuePath = "UnitName";
            Substitution_Units.SelectedIndex = 0;
        }

   

       
    }
}
